package com.tanhan.mindapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhan.mindapp.dao.SysRole;
import com.tanhan.mindapp.dao.SysUserRole;
import com.tanhan.mindapp.mapper.SysUserRoleMapper;
import com.tanhan.mindapp.service.SysRoleService;
import com.tanhan.mindapp.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignRolesToUser(String userId, List<String> roleIds) {
        // 先删除用户原有的所有角色
        this.removeRolesByUserId(userId);

        // 批量插入新的用户角色关系
        if (roleIds != null && !roleIds.isEmpty()) {
            List<SysUserRole> userRoles = roleIds.stream()
                    .map(roleId -> {
                        SysUserRole userRole = new SysUserRole();
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        return userRole;
                    })
                    .collect(Collectors.toList());
            return this.saveBatch(userRoles);
        }
        return true;
    }

    public List<String> getRoleIdsByUserId(String userId) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<SysUserRole> userRoles = this.list(queryWrapper);

        return userRoles.stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
    }

    // 通过userId获取用户的角色
    @Override
    public List<SysRole> getRolesByUserId(String userId) {
        List<String> roleIds = getRoleIdsByUserId(userId);
        // 处理空列表情况，避免SQL语法错误
        if (roleIds == null || roleIds.isEmpty()) {
            return Collections.emptyList();
        }
        return sysRoleService.listByIds(roleIds);
    }

    @Override
    public boolean removeRolesByUserId(String userId) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.remove(queryWrapper);
    }
}
